/*
 * This code belongs to
 * Krishna Brahmam, Dept. of CSE, IIT Guwahati
 */

package speech;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JFileChooser;

/**
 * Class MainGUI is the main GUI console.
 * @author  Krishna Brahmam
 */
public class MainGUI extends javax.swing.JFrame {
    private TargetDataLine inline;
    private SourceDataLine outline;
    private DataInputStream dataIn;
    private TrainingGUI trainGUI;
    private TestingGUI testGUI;
    private SettingsGUI settings;
    
    /* Default Settings */
    private int order = 12;
    private int frameLength = 300;
    private int frameShift = 100;
    private int codebookSize = 256;
    private int states = 6;
    private int numberOfHMMs;
    private String train_dir = "";
    private String test_dir = "";
    private String testDirectory = "";
    private String indexFile = "index.dat";
    private String listFile = "files.dat";
    private String testList = "test.dat";
    private String codebook = "final.cbk";
    private String outputWordlist = "out.dat";
    
    /** Creates new form MainGUI */
    public MainGUI() {
        initComponents();
        setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        filename = new javax.swing.JTextField();
        captureButton = new javax.swing.JButton();
        stopButton = new javax.swing.JButton();
        saveBrowseBrowse = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        playButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        playFileName = new javax.swing.JTextField();
        openBrowseButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        generalSettingsMenuItem = new javax.swing.JMenuItem();
        trainingMenuItem = new javax.swing.JMenuItem();
        testingMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Main");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Record"));

        jLabel1.setText("File Name");

        filename.setText("sample.wav");
        filename.setToolTipText("Name of the file");

        captureButton.setText("Capture");
        captureButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                captureButtonActionPerformed(evt);
            }
        });

        stopButton.setText("Stop");
        stopButton.setEnabled(false);
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        saveBrowseBrowse.setText("Browse");
        saveBrowseBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBrowseBrowseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(filename, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(saveBrowseBrowse)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(captureButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(stopButton)
                .addGap(37, 37, 37))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(filename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveBrowseBrowse)
                    .addComponent(captureButton)
                    .addComponent(stopButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Playback"));

        playButton.setText("Play");
        playButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("File Name");

        playFileName.setEditable(false);
        playFileName.setText("sample.wav");

        openBrowseButton.setText("Browse");
        openBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openBrowseButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(playFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(openBrowseButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(playButton)
                .addContainerGap(118, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(openBrowseButton)
                    .addComponent(playButton)
                    .addComponent(playFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jMenu1.setText("Application");

        generalSettingsMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        generalSettingsMenuItem.setText("General Settings");
        generalSettingsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generalSettingsMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(generalSettingsMenuItem);

        trainingMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
        trainingMenuItem.setText("Training");
        trainingMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                trainingMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(trainingMenuItem);

        testingMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        testingMenuItem.setText("Testing");
        testingMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testingMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(testingMenuItem);
        jMenu1.add(jSeparator2);

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setText("Quit");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Help");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMenuItem1.setText("Help Contents");
        jMenu2.add(jMenuItem1);
        jMenu2.add(jSeparator1);

        jMenuItem2.setText("About");
        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(163, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void captureButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_captureButtonActionPerformed
    captureButton.setEnabled(false);
    stopButton.setEnabled(true);
    // CaptureAudio into file
    captureAudio();
}//GEN-LAST:event_captureButtonActionPerformed

private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
    stopButton.setEnabled(false);
    captureButton.setEnabled(true);
    // Stop capturing 
    inline.stop();
    inline.close();
}//GEN-LAST:event_stopButtonActionPerformed

private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playButtonActionPerformed
    play();
}//GEN-LAST:event_playButtonActionPerformed
private void openBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openBrowseButtonActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    if(JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(this)){
        playFileName.setText(fileChooser.getSelectedFile().getAbsolutePath());
    }
}//GEN-LAST:event_openBrowseButtonActionPerformed
private void saveBrowseBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBrowseBrowseActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    if(JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)){
        playFileName.setText(fileChooser.getSelectedFile().getAbsolutePath());
    }
}//GEN-LAST:event_saveBrowseBrowseActionPerformed

private void trainingMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trainingMenuItemActionPerformed
    trainGUI = new TrainingGUI(this);
    trainGUI.setVisible(true);
}//GEN-LAST:event_trainingMenuItemActionPerformed

private void generalSettingsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generalSettingsMenuItemActionPerformed
    settings = new SettingsGUI(this);
    settings.setVisible(true);
}//GEN-LAST:event_generalSettingsMenuItemActionPerformed

private void testingMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testingMenuItemActionPerformed
    testGUI = new TestingGUI(this);
    testGUI.setVisible(true);
}//GEN-LAST:event_testingMenuItemActionPerformed

private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
    System.exit(0);
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void captureAudio(){
    AudioFormat format = new AudioFormat(AudioRecorder.sampleRate,
                                        AudioRecorder.bitSize,
                                        AudioRecorder.channels,
                                        AudioRecorder.signed,
                                        AudioRecorder.bigEndian);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);
    if(!AudioSystem.isLineSupported(info)){
        System.err.println("Line not supported");
        return;
    }
    try{
        inline = (TargetDataLine) AudioSystem.getLine(info);
        new AudioRecorder(inline,format,filename.getText()).start();
    }
    catch(LineUnavailableException e){
        System.err.println(e.getMessage());
    }
}
private void play(){
    byte[] data = new byte[1024];
    int numBytesRead = -1;
    AudioFormat format = new AudioFormat(AudioRecorder.sampleRate,
                                        AudioRecorder.bitSize,
                                        AudioRecorder.channels,
                                        AudioRecorder.signed,
                                        AudioRecorder.bigEndian);
    DataLine.Info info = new DataLine.Info(SourceDataLine.class,format);
    if(!AudioSystem.isLineSupported(info)){
        System.err.println("Line not supported");
        return;
    }
    try{
        outline = (SourceDataLine) AudioSystem.getLine(info);
        dataIn = new DataInputStream(new FileInputStream(playFileName.getText()));
        outline.open(format);
        outline.start();
        while(true){
            numBytesRead = dataIn.read(data);
            if(numBytesRead == -1) break;
            outline.write(data, 0, numBytesRead);
        }
        outline.drain();
        outline.stop();
        outline.close();
        outline = null;
    }
    catch(LineUnavailableException ex){
        System.err.println(ex.getMessage());
    }
    catch(FileNotFoundException ex){
        System.err.println(ex.getMessage());
    }
    catch(IOException ex){
        System.err.println(ex.getMessage());
    }
}
public void setParams(int order, int frameLength, int frameShift, 
        int codebookSize, int states){
    this.order = order;
    this.frameLength = frameLength;
    this.frameShift = frameShift;
    this.codebookSize = codebookSize;
    this.states = states;
}
public void setDirectoryPaths(String train_dir, String test_dir){
    this.train_dir = train_dir;
    this.test_dir = test_dir;
}
public void setFileNames(String index, String list, String codebook){
    this.indexFile = index;
    this.listFile = list;
    this.codebook = codebook;
}
public void setTestFileNames(String testList, String output, String test_dir){
    this.testList = testList;
    this.outputWordlist = output;
    this.testDirectory = test_dir;
}
public void setNumberOfHMMs(int num){
    this.numberOfHMMs = num;
}
public int getOrder(){
    return order;
}
public int getFrameLength(){
    return frameLength;
}
public int getFrameShift(){
    return frameShift;
}
public int getCodebookSize(){
    return codebookSize;
}
public int getStates(){
    return states;
}
public String getSamplesDirectory(){
    return train_dir;
}
public String getTestSamplesDirectory(){
    return test_dir;
}
public String getTestDirectory(){
    return testDirectory;
}
public String getIndexFileName(){
    return indexFile;
}
public String getListFileName(){
    return listFile;
}
public String getCodebookFileName(){
    return codebook;
}
public String getOutputWordlist(){
    return outputWordlist;
}
public String getTestListFileName(){
    return testList;
}
public int getNumberOfHMMs(){
    return numberOfHMMs;
}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton captureButton;
    private javax.swing.JTextField filename;
    private javax.swing.JMenuItem generalSettingsMenuItem;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JButton openBrowseButton;
    private javax.swing.JButton playButton;
    private javax.swing.JTextField playFileName;
    private javax.swing.JButton saveBrowseBrowse;
    private javax.swing.JButton stopButton;
    private javax.swing.JMenuItem testingMenuItem;
    private javax.swing.JMenuItem trainingMenuItem;
    // End of variables declaration//GEN-END:variables

}
